#!/bin/bash
discoverySSDDisk()
{
diskList=$(ls -1 /dev/sd* |  grep -E 'sd[a-zA-Z]+$' |  awk -F/ '{print $3}')
  
#filter usb block
for i in $diskList; do
    udevadm info --query=all --name=/dev/$i |grep 'ID_BUS=usb' &>/dev/null
    if [ $? -eq 0 ]; then
        local diskList=$(echo $diskList | sed "s/$i//g")
    else
        continue
    fi
done
#discovery SSD Device
for i in $diskList; do
    /usr/sbin/smartctl -a  /dev/$i |grep  "rpm"  &>/dev/null
    if [ $? -ne 0 ]; then
    continue      
    else
     
        local diskList=$(echo $diskList | sed "s/$i//g")
    fi
done
  
for i in $diskList ; do
    /usr/sbin/smartctl -a /dev/$i |grep  -E "Percent_Lifetime_Remain|Media_Wearout_Indicator|Wear_Leveling_Count" &>/dev/null
    if [ $? -ne 0 ]; then
        local diskList=$(echo $diskList |  sed "s/$i//g")
        for x in {0..1}; do
            local diskList=$(echo "$diskList $i$x")
        done
    else
        continue
    fi
  
  
  
done
  
local nvmeList=$(lsblk -d -o name,tran | grep "nvme" |awk '{print $1}')
local diskList=($(echo $diskList $nvmeList))
  
local length=${#diskList[@]}
printf "{\n"
printf  '\t'"\"data\":["
for ((i=0;i<$length;i++))
do
        printf '\n\t\t{'
        printf "\"{#DISK_NAME}\":\"${diskList[$i]}\"}"
        if [ $i -lt $[$length-1] ];then
                printf ','
        fi
done
printf  "\n\t]\n"
printf "}\n"
}


#GetDisk lifespan
diskCheck()
{
local diskName=$1
echo $diskName |grep -i nvme &>/dev/null && Type=nvme
echo $diskName |grep -E 'sd[a-zA-Z]+$' &>/dev/null && Type=nonraid
echo $diskName |grep -E 'sd[a-zA-Z]+[0-9]$' &>/dev/null && Type=raid
  
case $Type in
    nonraid)
        diskPercent=$(/usr/sbin/smartctl -a /dev/$diskName |grep  -E "Percent_Lifetime_Remain|Available_Reservd_Space|Wear_Leveling_Count" |awk '{print $4}')
        ;;
    raid)
        local Name=$(echo $diskName |sed 's/[0-9]//g' )
        local NUM=$(echo $diskName |sed 's/[a-zA-Z]//g' )
        diskPercent=$(/usr/sbin/smartctl -a  -l ssd  /dev/$Name -d sat+cciss,$NUM|grep -E "Percent_Lifetime_Remain|Media_Wearout_Indicator|Wear_Leveling_Count" |awk '{print $4}')   
        if [ -z "$diskPercent" ]; then
     diskPercent=$(/usr/sbin/smartctl -a  -l ssd  /dev/$Name -d aacraid,0,0,$NUM|grep -E "Percent_Lifetime_Remain|Media_Wearout_Indicator|Wear_Leveling_Count" |awk '{print $4}')
    fi
        ;;
    nvme)
        diskPercent=$(/usr/sbin/smartctl -a /dev/$diskName |grep -i "Percentage Used:"| awk -F: '{print $2}' |sed s/[[:space:]]//g| sed 's/\%//g'|awk '{print 100-$1}')
        ;;
esac
    echo $diskPercent
}


case $1 in
    discovery)
        discoverySSDDisk
        ;;
    *)
        diskCheck $1
        ;;
esac